package com.itao.jsqlparser;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.*;

import java.util.HashMap;
import java.util.Map;

/**
 * sql解析
 * @Author sjt
 * @CreateTime 2023/12/08 10:52
 */
public class SqlAnalyzing {
    public static void main(String[] args) throws JSQLParserException {

        var select = (Select)CCJSqlParserUtil.parse("SELECT col1 AS a, col2 AS b, col3 AS c FROM table WHERE col1 = 10 AND col2 = 20 AND col3 = 30");

        Map<String, Expression> map = new HashMap<>();
        var plainSelect = (PlainSelect)select.getSelectBody();
        var where1 = plainSelect.getWhere();
        System.out.println(where1);
        System.out.println(where1.getClass());
        Expression expression = CCJSqlParserUtil.parseExpression("col4 = 40");
        var orExpression = new OrExpression(where1, expression);
        plainSelect.setWhere(orExpression);
        var where = plainSelect.getWhere();
        System.out.println(where);
        System.out.println(where.getClass());
        for (SelectItem selectItem : plainSelect.getSelectItems()) {
            selectItem.accept(new SelectItemVisitorAdapter() {
                @Override
                public void visit(SelectExpressionItem item) {
                    map.put(item.getAlias().getName(), item.getExpression());
                }
            });
        }
        System.out.println("map " + map);
    }
}
